package com.shxc.smarttrade.login.activity;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.shxc.smarttrade.R;
import com.shxc.smarttrade.base.NoActionBarBaseActivity;
import com.shxc.smarttrade.info.Contents;
import com.shxc.smarttrade.login.model.LoginModel;
import com.shxc.smarttrade.old.utils.CloseAllActivity;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisModel;
import com.shxc.smarttrade.utils.analysis.JsonAnalysisUtils;
import com.shxc.smarttrade.utils.AppUtils;
import com.shxc.smarttrade.utils.Loger;
import com.shxc.smarttrade.utils.MyOkHttpUtils;
import com.shxc.smarttrade.utils.ToastUtils;

import org.xchris.view.annotation.ContentView;
import org.xchris.view.annotation.Event;
import org.xchris.view.annotation.ViewInject;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import okhttp3.Call;

/**
 * 登录主页
 */
@ContentView(R.layout.activity_login_home)
public class LoginHomeActivity extends NoActionBarBaseActivity {

    private InputMethodManager imm;

    @ViewInject(R.id.email_warning)
    TextView email_warning;
    @ViewInject(R.id.email_edittext)
    EditText email_edittext;
    @ViewInject(R.id.email_line)
    View email_line;
    @ViewInject(R.id.pass_warning)
    TextView pass_warning;
    @ViewInject(R.id.pass_edittext)
    EditText pass_edittext;
    @ViewInject(R.id.visible_imageview)
    ImageView visible_imageview;
    @ViewInject(R.id.pass_line)
    View pass_line;
    @ViewInject(R.id.login_textview)
    TextView login_textview;

    private int RED = Color.parseColor("#E24C4F");
    private int BLUE = Color.parseColor("#141F2B");
    private int GRAY = Color.parseColor("#B3B3B3");
    private int UNCLICK = Color.parseColor("#50141F2B");

    private String email = "";
    private String pass = "";

    private boolean canSee = false;

    @Event({R.id.close_imageview, R.id.login_textview, R.id.forget_view, R.id.register_view, R.id.visible_imageview})
    private void onClickk(View view) {

        switch (view.getId()) {
            case R.id.close_imageview:
                finish();
                break;
            case R.id.login_textview:
                //登录
                login();
                break;
            case R.id.forget_view:
                //忘记密码
                JumpTo(LoginForgetPassActivity.class);
                break;
            case R.id.register_view:
                //注册
                pass_edittext.setText("");
                JumpTo(LoginRegiterActivity.class);
                break;
            case R.id.visible_imageview:
                canSee = !canSee;
                if (canSee) {
                    visible_imageview.setImageResource(R.mipmap.xianshi_icon);
                    pass_edittext.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    visible_imageview.setImageResource(R.mipmap.yingcang_icon);
                    pass_edittext.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                break;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        setListener();
        isEnable();
    }

    @Override
    protected void onResume() {
        super.onResume();
        email_edittext.setText(spImp.getEmail());
    }

    private void setListener() {

        //判断是否获取焦点 - email
        email_edittext.setOnFocusChangeListener(new android.view.View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    email_line.setBackgroundColor(BLUE);
                } else {
                    // 此处为失去焦点时的处理内容
                    email_line.setBackgroundColor(GRAY);
                    checkContent();
                }
            }
        });

        //判断内容 - email
        email_edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    email_warning.setVisibility(View.VISIBLE);
                    email_warning.setTextColor(GRAY);
                    email_warning.setText("电子邮箱");
                } else {
                    email_warning.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                isEnable();
            }
        });

        //判断是否获取焦点 - pass
        pass_edittext.setOnFocusChangeListener(new android.view.View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    pass_line.setBackgroundColor(BLUE);
                } else {
                    // 此处为失去焦点时的处理内容
                    pass_line.setBackgroundColor(GRAY);
                    checkContent();
                }
            }
        });

        //判断内容 - pass
        pass_edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    pass_warning.setVisibility(View.VISIBLE);
                    pass_warning.setTextColor(GRAY);
                    pass_warning.setText("密码");
                } else {
                    pass_warning.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                isEnable();
            }
        });
    }

    private void isEnable() {
        int errors = 0;
        email = email_edittext.getText().toString();
        pass = pass_edittext.getText().toString();
        //电子邮箱
        if (AppUtils.isEmpty(email)) {
            errors++;
        } else if (!AppUtils.isEmail(email)) {
            errors++;
        }

        if (AppUtils.isEmpty(pass)) {
            errors++;
        } else if (pass.length() < 6 || pass.length() > 16 || AppUtils.isNumeric(pass) || pass.matches("^[a-zA-Z]*")) {
            errors++;
        }

        if (errors == 0) {
            login_textview.setEnabled(true);
            login_textview.setBackgroundColor(BLUE);
        } else {
            login_textview.setEnabled(false);
            login_textview.setBackgroundColor(UNCLICK);
        }
    }

    //校验输入内容
    private void checkContent() {

        int errors = 0;

        email = email_edittext.getText().toString();
        pass = pass_edittext.getText().toString();

        //电子邮箱
        if (AppUtils.isEmpty(email)) {
            email_warning.setVisibility(View.GONE);
            errors++;
        } else if (!AppUtils.isEmail(email)) {
            email_warning.setVisibility(View.VISIBLE);
            email_warning.setTextColor(RED);
            email_warning.setText("请输入有效的邮箱");
            errors++;
        } else {
            email_warning.setVisibility(View.VISIBLE);
            email_warning.setTextColor(GRAY);
            email_warning.setText("电子邮箱");
        }

        if (AppUtils.isEmpty(pass)) {
            pass_warning.setVisibility(View.GONE);
            errors++;
        } else if (pass.length() < 6 || pass.length() > 16 || AppUtils.isNumeric(pass) || pass.matches("^[a-zA-Z]*")) {
            pass_warning.setVisibility(View.VISIBLE);
            pass_warning.setTextColor(RED);
            pass_warning.setText("密码必须由6-16位数字与字母组成");
            errors++;
        } else {
            pass_warning.setVisibility(View.VISIBLE);
            pass_warning.setTextColor(GRAY);
            pass_warning.setText("密码");
        }

        if (errors == 0) {
            login_textview.setEnabled(true);
            login_textview.setBackgroundColor(BLUE);
        } else {
            login_textview.setEnabled(false);
            login_textview.setBackgroundColor(UNCLICK);
        }
    }

    // 点击EditText以外的任何区域隐藏键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (v != null) {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    //登录
    private void login() {
        loadingDialog.show();
        Map<String, Object> map = new HashMap<>();
        map.put("email", email);
        map.put("password", pass);

        MyOkHttpUtils.getServiceDatas(map, Contents.LOGIN, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int d) {
                Loger.e("response", response);
                if (response != null) {
                    JsonAnalysisModel jam = JsonAnalysisUtils.jsonAnalysis(response, LoginModel.class);
                    if (jam.isSuccess()) {
                        LoginModel model = (LoginModel) jam.getData();
                        if (model.getErr_code().equals("0")) {
//                            ToastUtils.showToast("登录成功");
                            SpUtils.putString(getApplicationContext(), "accessToken", model.getData().getUser().getAccessToken());
                            spImp.setRongimtoken(model.getData().getUser().getAccessToken());
                            SpUtils.putInt(getApplicationContext(), "type", model.getData().getUser().getType());
                            spImp.setAccType(model.getData().getUser().getType());
                            SpUtils.putInt(getApplicationContext(), "userId", model.getData().getUser().getUserId());
                            spImp.setUserId(model.getData().getUser().getUserId());
                            SpUtils.putBoolean(getApplicationContext(), "isLogin", true);
                            spImp.setLogin(true);
                            SpUtils.putBoolean(getApplicationContext(), "firstOpen", false);
                            SpUtils.putBoolean(getApplicationContext(), "firstLogin", model.getData().getUser().isFirstLogin());

                            spImp.setEmail(email);
                            spImp.setInviteCode(model.getData().getUser().getInviteCode());

                            //友盟
//                            MobclickAgent.onProfileSignIn(ub.getTelephone());
                            //設置别名
                            setMsgSetAlias(model.getData().getUser().getInviteCode());
                            //弹出之前的Activity
                            CloseAllActivity.getScreenManager().clearEcxeptMainActivity();

                            finish();
                        } else {
                            ToastUtils.showToast(jam.getMsg());
                        }

                    } else {
                        ToastUtils.showToast(jam.getMsg());
                    }
                }
                loadingDialog.dismiss();
            }

            @Override
            public void faild(Call call, Exception e, int id) {
                loadingDialog.dismiss();
            }
        });
    }

    /**
     * 设置别名
     *
     * @param alias 别名
     */
    public void setMsgSetAlias(String alias) {
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }


    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.e("", "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String Logers;
            switch (code) {
                case 0:
                    Logers = "Set tag and alias success";
                    Loger.e("Login", Logers);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    Logers = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Loger.e("Login", Logers);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    Logers = "Failed with errorCode = " + code;
                    Loger.e("Login", Logers);
            }
        }
    };
}
